<?php

namespace Game\Controller;

use Common\Controller\BaseController;

class ImageController extends BaseController
{

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 上传图片
     */
    public function doUpload()
    {
        $imgMaxSize = 3;
        $fileData = $_FILES['file'];
        if ($fileData['error'] != 0) {
            $this->ajaxReturn(static::$res->err('图片上传失败！'));
        }
        $fileInfo = getimagesize($fileData['tmp_name']);
        $mime = $fileInfo['mime'];

        if (preg_match('/image\/\w+/', $mime) != 1) {
            $this->ajaxReturn(static::$res->err('仅支持图像上传！'));
        }

        if ($fileData['type'] > $imgMaxSize * 1024 * 1024) {
            $this->ajaxReturn(static::$res->err('图像大于' . $imgMaxSize . 'M'));
        }

        $oldImgName = $fileData['name'];
        if (strrpos($oldImgName, '.')) {
            $imgType = substr($oldImgName, strrpos($oldImgName, '.') + 1);
        } else {
            $imgType = 'jpeg';
        }

        $imgBase64 = base64_encode(file_get_contents($fileData['tmp_name']));

        $imageUri = "/ImgFile/UserUpload/" . date("Ymd") . "/" . time() . "_" . rand(1111, 9999) . '.' . $imgType;
        $fileName = WEB_PATH . $imageUri;

        if (!saveImg($imgBase64, $fileName)) {
            $this->ajaxReturn(static::$res->err('图片存储失败'));
        }
        $photoUri = "" . $imageUri;
        $this->ajaxReturn(static::$res->suc('成功', $photoUri));
    }

}
